package com.yc;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: concurrent
 * @description: ServerSocket
 * @author: zy
 * @create: 2022-01-13 11:22
 */
public class Test4_Server_ReaderWriter {
    public static void main(String[] args) throws IOException {
        final int port = 10000;
        ServerSocket ss = null;
        for (int i = 10000; i < 65535; i++) {
            try {
                //完成一台时间服务
                ss = new ServerSocket(i);
                break;
            } catch (Exception ex) {
                ex.printStackTrace();
                if (ex instanceof BindException) {
                    System.out.println("端口:" + i + "已经被占用");
                }
            }
        }
        System.out.println(ss.getInetAddress().getHostName() + "启动了,监听了端口号: ****" + ss.getLocalPort() + "***...");

        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date d = null;
        String time = null;

        while (true) {
            //获取一个与客户端的套接字
            Socket s = ss.accept();   //阻塞式的方法
            System.out.println("获取了一个与客户端:" + s.getRemoteSocketAddress() + "的联接");
            d = new Date();
            time = df.format(d);

            //套接字编程的底层就是io, 这是什么流.   输入  |  输出
            //   转换流，将字节流转为字符流
            try (OutputStreamWriter oos = new OutputStreamWriter(s.getOutputStream());) {
                oos.write(time);
                oos.flush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            s.close();
            System.out.println("服务端断开与客户端的联接");


        }
    }

}
